package com.it135.citytraffic.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.it135.citytraffic.pojo.dto.AddCrossingDTO;
import com.it135.citytraffic.pojo.entity.Crossing;
import com.it135.citytraffic.pojo.entity.RoadCache;
import com.it135.citytraffic.pojo.entity.RoadStatistic;
import com.it135.citytraffic.pojo.result.Result;
import com.it135.citytraffic.pojo.vo.CrossingInfoVO;
import com.it135.citytraffic.pojo.vo.CrossingVO;
import com.it135.citytraffic.service.ICrossingService;
import com.it135.citytraffic.service.IRoadCacheService;
import com.it135.citytraffic.service.IRoadStatisticService;
import com.it135.citytraffic.utils.BeanCopyTool;
import com.it135.citytraffic.utils.RoadAnalyseUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 动态检测的路口 前端控制器
 * </p>
 *
 * @author lh
 * @since 2024-05-23
 */
@RestController
@Data
@Slf4j
@RequestMapping("/api/crossing")
public class CrossingController {

    private final ICrossingService crossingService;
    private final IRoadStatisticService iRoadStatisticService;
    private final RoadAnalyseUtils roadAnalyseUtils;
    private final IRoadCacheService iRoadCacheService;

    private final RedisTemplate<Long,Object> redisTemplate;

    private final String NAME = "name";
    private final String ANALYSE_CACHE = "analyseCache";
    private final String REASON_ANALYSE_CACHE = "reasonAnalyseCache";
    private final String SUGGESTION = "suggestion";
    private final String ANALYSE_LAST_UPDATE = "analyseLastUpdate";


    @GetMapping
    @CrossOrigin
    public Result<List<CrossingVO>> getCrossing() {
        List<Crossing> list = crossingService.list();
        List<CrossingVO> crossingVOS = BeanCopyTool.convertCopyList(list, CrossingVO.class);
        return Result.success(crossingVOS);
    }

    @PostMapping
    @CrossOrigin
    public Result<Long> AddCrossing(AddCrossingDTO addCrossingDTO) {
        log.info("addCrossingDTO:{}", addCrossingDTO);
        Crossing crossing = new Crossing();
        BeanUtils.copyProperties(addCrossingDTO, crossing);
        crossing.setCreateTime(LocalDateTime.now());
        Long id = crossingService.insert(crossing);
        return Result.success(id);
    }

    @GetMapping("/history/{id}")
    @CrossOrigin
    public Result<CrossingInfoVO> getCrossingAnalyse(@PathVariable Long id) {
        HashOperations<Long,String,String> hashOperations = redisTemplate.opsForHash();
        if (hashOperations.get(id,ANALYSE_CACHE) == null || hashOperations.get(id,REASON_ANALYSE_CACHE) == null
        || hashOperations.get(id,SUGGESTION) == null) {
            Crossing crossing = crossingService.getById(id);
            if(crossing==null)return Result.error("参数错误:不存在id为"+id+"的路口!");

            if (crossing.getAnalyseCache() == null || crossing.getReasonAnalyseCache() == null
                    || crossing.getSuggestion() == null)
                return Result.error("请稍后重试 或者进行实时分析");


            hashOperations.put(crossing.getId(), NAME, crossing.getName());
            hashOperations.put(crossing.getId(), SUGGESTION, crossing.getSuggestion());
            hashOperations.put(crossing.getId(), REASON_ANALYSE_CACHE, crossing.getReasonAnalyseCache());
            hashOperations.put(crossing.getId(), ANALYSE_CACHE, crossing.getAnalyseCache());
            hashOperations.put(crossing.getId(), ANALYSE_LAST_UPDATE, String.valueOf(crossing.getAnalyseLastUpdate()));

            return Result.success(new CrossingInfoVO(crossing.getId(), crossing.getName(),
                    crossing.getAnalyseCache(), crossing.getReasonAnalyseCache(),
                    crossing.getSuggestion(), crossing.getAnalyseLastUpdate()));
        } else {
            String roadName = hashOperations.get(id, NAME);
            String analyseCache = hashOperations.get(id, ANALYSE_CACHE);
            String reasonAnalyseCache = hashOperations.get(id, REASON_ANALYSE_CACHE);
            String suggestion = hashOperations.get(id, SUGGESTION);
            String date = hashOperations.get(id, ANALYSE_LAST_UPDATE);
            LocalDateTime analyseLastUpdate = LocalDateTime.parse(date);

            return Result.success(CrossingInfoVO.builder()
                    .roadName(roadName)
                    .id(id)
                    .timeAnalyse(analyseCache)
                    .reasonAnalyse(reasonAnalyseCache)
                    .suggestion(suggestion)
                    .lastUpdateTime(analyseLastUpdate)
                    .build());
        }
    }


    @CrossOrigin
    @DeleteMapping("/{id}")
    public Result<String> DeleteCrossing(@PathVariable Long id) {
        crossingService.removeById(id);
        return Result.success("删除成功");
    }

    @CrossOrigin
    @DeleteMapping
    public Result<String> DeleteCrossingList(@RequestParam List<Long> ids) {
        crossingService.removeByIds(ids);
        return Result.success("删除成功");
    }
    @CrossOrigin
    @PutMapping
    public Result<String> UpdateStatus(@RequestBody Crossing crossing) {
        crossingService.updateStatus(crossing);
        return Result.success("修改成功!");
    }

    /**
     * 路口和路段预测
     *
     * @param id 路口id
     * @return 预测结果
     */
    @CrossOrigin
    @GetMapping("/predict/{id}")
    public Result<String> predictCrossing(@PathVariable Long id) {
        String predict_crossing_block = crossingService.predictCrossing(id);
        String predict_road = crossingService.predictRoad(id);
        if (predict_road == null || predict_road.isEmpty()) {
            return Result.success(predict_crossing_block + "<br>该路口中路段拥堵或严重拥堵的概率不超过40%");
        } else {
            return Result.success(predict_crossing_block + "<br>下面是该路口中路段的预测:<br>" + predict_road);
        }
    }

}
